//
//  TTShopCartMultyViewCell.m
//  TaoTuo
//
//  Created by admin on 2019/9/2.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTShopCartMultyViewCell.h"
#import "TTShopCartDiamondViewCell.h"
#import "TTShopCartCommodityViewCell.h"
#import "TTShopCartSubDetailModel.h"
#import "TTShopCartMultyModel.h"
#import "TTGoodsDetailViewController.h"
#import "YBImageBrowser.h"
#import "TTDiamondDetailViewController.h"
#import "TTQualityCheckModel.h"

#define sectionHeaderViewH 40

static NSString *cell_diamond_id_cell = @"cell_diamond_id_cell";
static NSString *cell_commodity_id_cell = @"cell_commodity_id_cell";


@interface TTShopCartMultyViewCell ()<UITableViewDelegate, UITableViewDataSource, TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) TTShopCartMultyModel *multyModel;
@property (nonatomic, assign) BOOL canSelect;
@property (nonatomic, assign) BOOL sectionViewCanSelect;    // 能不能选区头

@property (nonatomic, assign) BOOL isFromCommitOrder;   // 是否来自提交订单页面

@end

@implementation TTShopCartMultyViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)setMultyModel:(TTShopCartMultyModel *)multyModel canSelect:(BOOL)canSelect sectionViewCanSelect:(BOOL)sectionViewCanSelect isFromCommitOrder:(BOOL)isFromCommitOrder
{
    [self setMultyModel:multyModel canSelect:canSelect sectionViewCanSelect:sectionViewCanSelect];
    self.isFromCommitOrder = isFromCommitOrder;
}

- (void)setMultyModel:(TTShopCartMultyModel *)multyModel canSelect:(BOOL)canSelect sectionViewCanSelect:(BOOL)sectionViewCanSelect
{
    self.multyModel = multyModel;
    self.canSelect = canSelect;
    self.sectionViewCanSelect = sectionViewCanSelect;
    
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:multyModel.array];
    
    BOOL enabled = NO;
    for (TTShopCartSubDetailModel *model in multyModel.array) {
        if (model.Status.intValue == 1) {
            enabled = YES;
            break;
        }
    }
    if (enabled) {
        // 如果有可售的
        BOOL select = YES;
        for (TTShopCartSubDetailModel *model in multyModel.array) {
            if (!model.isSelect && model.Status.intValue == 1) {
                select = NO;
                break;
            }
        }
        multyModel.isSelect = select;
    }
    
    
    self.bgView.height = multyModel.cellHeight + sectionHeaderViewH;
    self.tableView.height = self.bgView.height;
    self.bgView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bgView.bounds cornerRadius:5].CGPath;

    [self.tableView reloadData];
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    
    if (model.GoodsType == 1) {
        // 裸石
        TTShopCartDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_diamond_id_cell];
        [cell setDetailModel:model hasShadow:NO canSelect:self.canSelect isFromCommitOrder:self.isFromCommitOrder];
        cell.delegate = self;
        return cell;
    } else {
        TTShopCartCommodityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_commodity_id_cell];
        [cell setDetailModel:model hasShadow:NO canSelect:self.canSelect isFromCommitOrder:self.isFromCommitOrder];
        cell.delegate = self;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    
    if (!self.sectionViewCanSelect) {
        model.isSelect = !model.isSelect;
        [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"chooseShop_key" object:model];
        return;
    }
    
    if (model.GoodsType == 1) {
        // 可售的裸石
        if (model.Status.intValue == 1) {
            if ([self.delegate respondsToSelector:@selector(lookDiamondDetailWithMultyViewCell:goodsBarCode:)]) {
                [self.delegate lookDiamondDetailWithMultyViewCell:self goodsBarCode:model.GoodsBarCode];
            }
        }
        return;
    }
    
    TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:nil];
//    detailVC.styleLibraryId = model.StyleLibraryId;
    [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartSubDetailModel *model = self.dataArray[indexPath.row];
    return model.h;
    
}

#pragma mark - TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate
- (void)clickLeftButtonInCommodityViewCell:(TTShopCartCommodityViewCell *)cell
{
    [self setSectionViewSelect];
}

- (void)longGestureActionInCommodityViewCell:(TTShopCartCommodityViewCell *)cell deleteModel:(TTShopCartSubDetailModel * _Nullable)deleteModel
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self deleteHintWithIndexPath:indexPath];
}

- (void)clickLeftButtonInDiamondViewCell:(TTShopCartDiamondViewCell *)cell
{
    [self setSectionViewSelect];
}

- (void)longGestureActionInDiamondViewCell:(TTShopCartDiamondViewCell *)cell deleteModel:(TTShopCartSubDetailModel * _Nullable)deleteModel
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self deleteHintWithIndexPath:indexPath];
}

- (void)clickDeleteButtonInDiamondViewCell:(TTShopCartDiamondViewCell *)cell deleteModel:(TTShopCartSubDetailModel *)deleteModel
{
    if ([self.delegate respondsToSelector:@selector(shopCartMultyViewCell:deleteLuoshiModel:)]) {
        [self.delegate shopCartMultyViewCell:self deleteLuoshiModel:deleteModel];
    }
}

// 查看证书
- (void)clickLookCertificateWithModel:(TTShopCartSubDetailModel *)model
{
    [TTLoginSingle lookCertificateWithUrlString:model.CertPic];
}

// 删除提示
- (void)deleteHintWithIndexPath:(NSIndexPath *)indexPath
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(shopCartMultyViewCell:deleteModel:)]) {
        [self.delegate shopCartMultyViewCell:self deleteModel:self.dataArray[indexPath.row]];
    }
    
}

// 设置区头按钮是否选中
- (void)setSectionViewSelect
{
    BOOL allSel = YES;
    for (TTShopCartSubDetailModel *model in self.dataArray) {
        if (!model.isSelect && model.Status.intValue == 1) {
            allSel = NO;
            break;
        }
    }
    self.multyModel.isSelect = allSel;
    
    [self.tableView reloadData];
    
}

- (void)selectAllBtnClick:(UIButton *)sender
{
    BOOL canSelect = NO;
    for (TTShopCartSubDetailModel *model in self.dataArray) {
        if (model.Status.intValue == 1) {
            canSelect = YES;
            model.isSelect = !sender.selected;
        }
    }
    if (canSelect) {
        sender.selected = !sender.selected;
        
        self.multyModel.isSelect = sender.selected;
        
        [self.tableView reloadData];
        
        [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return sectionHeaderViewH;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bgView.width, sectionHeaderViewH)];
    
    UIButton *btn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"shopcart_unsel"] selectedImage:[UIImage imageNamed:@"shopcartlist_sel"] target:self action:@selector(selectAllBtnClick:)];
    btn.selected = self.multyModel.isSelect;
    [sectionView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.width.mas_equalTo(30 * kScale);
        make.top.height.equalTo(sectionView);
    }];
    
    [LLLineUtilies addLineInView:sectionView startPoint:CGPointMake(btn.right, sectionView.height) endPoint:CGPointMake(sectionView.width - 10, sectionView.height) lineColor:COLOR(232, 232, 234, 1)];
    
    CGFloat left;
    if (!self.sectionViewCanSelect) {
        left = 10;
        btn.hidden = YES;
    } else {
        left = 30 * kScale + 5;
        btn.hidden = NO;
    }
    
    UILabel *titleLabel = [UILabel labelWithTitle:self.multyModel.title color:[UIColor blackColor] fontSize:15];
    [sectionView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(left);
        make.right.lessThanOrEqualTo(sectionView).mas_offset(-150);
        make.centerY.equalTo(sectionView);
    }];
    
    UIButton *hintBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [hintBtn setImage:[UIImage imageNamed:self.multyModel.hintImageName] forState:UIControlStateNormal];
    [hintBtn setTitle:self.multyModel.hintInfo forState:UIControlStateNormal];
    [hintBtn setTitleColor:self.multyModel.hintInfoColor forState:UIControlStateNormal];
    hintBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [sectionView addSubview:hintBtn];
    [hintBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).mas_offset(2);
        make.centerY.equalTo(sectionView);
    }];
    
    if (self.multyModel.qualityCheckModel != nil) {
        UIButton *deleteBtn = [UIButton createButtonWithTitle:@"移除镶嵌" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:10] backgroundColor:kMainColor cornerRadius:9 target:self action:@selector(deleteButtonClick)];
        deleteBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 6);
        [sectionView addSubview:deleteBtn];
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(sectionView).mas_offset(-9);
            make.centerY.equalTo(sectionView);
            make.height.mas_equalTo(18);
        }];
        NSString *str = [NSString stringWithFormat:@"证书:%@", self.multyModel.qualityCheckModel.CertTypeName];
        UILabel *zsLabel = [UILabel labelWithTitle:str color:UIColorHex(666666) fontSize:12];
        [sectionView addSubview:zsLabel];
        [zsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(deleteBtn.mas_left).mas_offset(-9);
            make.centerY.equalTo(sectionView);
        }];
    }
    
    return sectionView;
}

// 移除已匹配的产品
- (void)deleteButtonClick
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteMatchedProductNotify_key" object:self.multyModel];
}

- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, SCREEN_WIDTH - 10, self.multyModel.array.count * 140 + sectionHeaderViewH)];
        _bgView.layer.cornerRadius = 5;
        _bgView.layer.shadowColor = kMainColor.CGColor;
        _bgView.layer.shadowOffset = CGSizeZero;
        _bgView.layer.shadowOpacity = 0.2;
        [self.contentView addSubview:_bgView];
    }
    return _bgView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.bgView.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.layer.cornerRadius = 5;
        _tableView.scrollsToTop = NO;
//        _tableView.rowHeight = 140;
//        _tableView.estimatedRowHeight = 140;    // 防止 reloadData 抖动
        _tableView.separatorInset = UIEdgeInsetsMake(0, 30 * kScale, 0, 10);
        [_tableView registerClass:[TTShopCartDiamondViewCell class] forCellReuseIdentifier:cell_diamond_id_cell];
        [_tableView registerClass:[TTShopCartCommodityViewCell class] forCellReuseIdentifier:cell_commodity_id_cell];
        [self.bgView addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
